package com.jacky.iot.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jacky.iot.commons.TaskType;
import com.jacky.iot.dtos.DataFetchWrapper;
import com.jacky.iot.dtos.TimeCmd;
import com.jacky.iot.models.CpuUsage;
import com.jacky.iot.service.CpuUsageService;
import com.jacky.iot.service.ScheduledTaskManager;
import com.jacky.iot.service.TaskWrapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "os/")
public class OSCollectionController {

    private ScheduledTaskManager taskManager;
    private CpuUsageService cpuUsageService;


    public OSCollectionController(ScheduledTaskManager taskManager, CpuUsageService cus) {
        this.taskManager = taskManager;
        this.cpuUsageService = cus;
    }

    @DeleteMapping("/cancelCollect")
    public void cancelOSInfoCollect() {
        List<TaskWrapper> taskWrappers = taskManager.getTaskWrappersByTaskType(TaskType.OS_COLLECT);
        taskWrappers.forEach(tw -> {
            Future<?> future = tw.getFuture();
            if (future != null && !future.isCancelled()) {
                future.cancel(false);
            }
        });
    }

    @GetMapping("/fetchRecentData")
    public List<CpuUsage> fetchRecentData() {
        DataFetchWrapper dfw = new DataFetchWrapper();
        dfw.setMeasurement("cup_usage");
        dfw.setFetchFields(Lists.newArrayList("usage", "system","_time"));
        Map<String, Object> tagMap = Maps.newHashMap();
        tagMap.put("host", "192.168.56.1");
        tagMap.put("cpu_core", "total");
        dfw.setTagMap(tagMap);

        TimeCmd timeCmd = new TimeCmd(5, TimeUnit.MINUTES);
        return cpuUsageService.fetchLastData(dfw, timeCmd);
    }

}
